// components/process-bar/process-bar.js
let movableAreaWith = 0
let movableViewWith = 0
const backgroundManager = wx.getBackgroundAudioManager()
let currentSec = -1   // 当前秒数
let duration = 0      // 总时长 s

// 设置锁, 进度条是否在拖拽(拖拽和 updateTime冲突)
let isMoving = isMoving
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isSame: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    // 移动距离
    movableDis: 0,
    percent: 0
  },

  lifetimes: {
    // 布局完成后
    ready() {
      // 同一首歌 重新获取当前长度
      if(this.properties.isSame && this.data.showTime.totalTime == '00:00'){
        this.setTime()
      }
      this._getMovableDis()
      this._bindBGMEvent()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event) {
      // console.log(event)
      // 拖动
      if(event.detail.source == 'touch') {
        // backgroundManager.pause()
        // 移动进度
        this.data.percent = event.detail.x / (movableAreaWith - movableViewWith) * 100
        this.data.movableDis = event.detail.x
        isMoving = true
      }
    },
    onTouchEnd() {
      // 调整进度条
      const currentTimeFormat = this._dataFormat(Math.floor(backgroundManager.currentTime))
      this.setData({
        percent: this.data.percent,
        movableDis: this.data.movableDis,
        ['showTime.currentTime']: `${currentTimeFormat.min}:${currentTimeFormat.sec}`,
      })
      // 调整音乐 秒为单位
      backgroundManager.seek(duration * this.data.percent / 100)
      // backgroundManager.play()
      isMoving = false
    },
    // 获取可移动距离
    _getMovableDis() {
      const query = this.createSelectorQuery()
      query.select('.movable-area').boundingClientRect()
      query.select('.movable-view').boundingClientRect()
      query.exec((rect) => {
        // console.log(rect)
        movableAreaWith = rect[0].width
        movableViewWith = rect[1].width
        // console.log(movableAreaWith, movableViewWith)
      })
    },
    _bindBGMEvent() {
      backgroundManager.onPlay(() => {
        console.log('onplay')
        isMoving = false
        this.triggerEvent('musicPlay')
      })

      backgroundManager.onStop(() => {
        console.log('onStop')
      })

      backgroundManager.onPause(() => {
        console.log('onPause')
        this.triggerEvent('musicPause')
      })

      backgroundManager.onWaiting(() => {
        console.log('onWaiting')
      })

      backgroundManager.onCanplay(() => {
        console.log('onCanplay')
        // console.log(backgroundManager.duration)
        if (typeof backgroundManager.duration != 'undefined'){
          this.setTime()
        }else {
          setTimeout(() => {
            this.setTime()
          }, 1000)
        }
      })

      // 音乐播放进度 只有前台才会触发
      backgroundManager.onTimeUpdate(() => {
        if(isMoving) return
        // console.log('onTimeUpdate')
        // 获取当前播放时间 , 优化每秒setData 一次
        const currentTime = backgroundManager.currentTime
        const duration = backgroundManager.duration
        const sec = currentTime.toString().split('.')[0]

        if(sec != currentSec) {
          const currentTimeFormat = this._dataFormat(currentTime)
          this.setData({
            movableDis: (movableAreaWith - movableViewWith) * (currentTime / duration),
            percent: (currentTime / duration) * 100,
            ['showTime.currentTime']: `${currentTimeFormat.min}:${currentTimeFormat.sec}`
          })
          currentSec = sec
          // console.log(currentSec)
          // 联动歌词
          this.triggerEvent('timeUpdate', {
            currentTime
          })
        }
        
        
        
      })
      /**
       * 组件调用父元素方法
       */
      backgroundManager.onEnded(() => {
        console.log('onEnded')
        this.triggerEvent('musicEnd')
      })

      backgroundManager.onError((res) => {
        console.log(res.errMsg, res.errCode)
        wx.showToast({
          title: '错误' + res.errCode,
        })
      })
    },
    // 设置总播放时长
    setTime(){
      duration = backgroundManager.duration
      // console.log(duration)
      const durationFormat = this._dataFormat(duration)
      // console.log(durationFormat)
      this.setData({
        ['showTime.totalTime']: `${durationFormat.min}:${durationFormat.sec}`
      })
      
    },
    _dataFormat(sec) {
      const min = Math.floor(sec / 60)
      sec = Math.floor(sec % 60)
      return {
        'min': this._parse0(min),
        'sec': this._parse0(sec)
      }
    },
    _parse0(num){
      return num < 10 ? '0' + num : num
    }
  }
})
